<!-- file upload widget -->
<script src="template/js/form/bootstrap-fileupload.js"></script>
<script type="text/javascript" src="template/js/ajaxfileupload.js"></script>

<!-- main content -->
<div class="container">
    <?php if ($user->getId() == 1) : ?>
        <div class="row-fluid">
            <div class="span12">
                <div class="w-box" id="n_word_character_limiter">
                    <div class="w-box-header">
                        <h4>НОВЫЙ НОМЕР</h4>
                    </div>
                    <div class="w-box-content cnt_a">
                        <div class="row-fluid">
                            <div class="span6">
                                <form id="create_sim" action="ajax/createSim.php" method="post">
                                    <input id="create_sim_number" name="create_sim_number" type="text" value=""
                                           placeholder="Введите номер" class="span6"><br/>
                                    <input id="create_sim_puk" name="create_sim_puk" type="text" value=""
                                           placeholder="Введите ICCID" class="span6">

                                    <div class="formSep sepH_b">
                                        <button id="create_sim_submit" class="btn btn-beoro-3" type="submit">Сохранить
                                        </button>
                                        <a href="#" class="btn btn-link">Отменить</a>
                                    </div>
                                </form>
                            </div>
                            <div class="span3">
                                <div class="fileupload fileupload-new" data-provides="fileupload">
                                    <div class="input-append">
                                        <div class="uneditable-input input-small">
                                            <i class="icon-file fileupload-exists"></i>
                                            <span class="fileupload-preview"></span>
                                        </div>
                                        <span class="btn btn-file">
                                            <span class="fileupload-new">Выберите файл</span>
                                            <span class="fileupload-exists">Изменить</span>
                                            <input name="fileToUpload" id="fileToUpload" type="file">
                                        </span>
                                        <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Удалить</a>&nbsp;
                                        <button id="buttonUpload" class="btn btn-beoro-3" type="submit"
                                                style="display: none;">Загрузить
                                        </button>
                                        <img id="loading" src="template/img/loading.gif" style="display:none;">
                                    </div>
                                </div>
                            </div>
                            <div class="span3">
                                <button class="btn btn-mini pop-over" data-html="true"
                                        data-content="<p><strong>1-я колонка:</strong> номера телефонов</p>
                                <p><strong>2-я колонка:</strong> ICCID</p>
                                <p>Файл должен быть <strong>без</strong> заголовка (без первой строки с названием колонок)</p>
                                <p>Файл должен быть создан и сохранен в программе <strong>Excel</strong> или аналогичной</p>
                                <p>Разделитель полей при обработке скриптом - ';' (точка с запятой)</p>"
                                        data-title="Формат файла CSV:" data-placement="bottom" data-trigger="hover">Справка</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
    <div class="row-fluid">
        <div class="span12">
            <div class="w-box hideable">
                <div class="w-box-header">
                    <h4>Пул номеров</h4>
                </div>
                <div class="w-box-content">
                    <table class="table table-vam table-striped" id="sim_list_table">
                        <thead>
                        <tr>
                            <th>№</th>
                            <th>ID</th>
                            <th>Номера</th>
                            <th>ICCID</th>
                            <th>Действия</th>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $(".remove_sim").live('click', function (e) {
            var del_sim = $(this).closest("tr");
            var del_sim_number = $(del_sim).children("td.sim_number").text();
            var del_sim_id = $(del_sim).children("td.sim_id").text();
            e.preventDefault();
            bootbox.confirm("Вы уверены что хотите удалить номер " + del_sim_number + " ?", function (confirmed) {
                if (confirmed == true) {
                    $.ajax({
                        url: "ajax/removeSim.php",
                        dataType: "json",
                        type: "POST",
                        data: {del_sim: del_sim_id},
                        success: function (data) {
                            $.sticky(data.message, {autoclose: 3000, position: "top-center", type: "st-success"});
                            loadDataSim('#sim_list_table', 'ajax/loadListSim.php');
                        },
                        error: function (data) {
                            $.sticky(data.message, {autoclose: 3000, position: "top-center", type: "st-error"});
                        }
                    });
                } else {
                    return false;
                }
            });
        });
    });
</script>
<script type="text/javascript">

    function loadDataSim(target, sAjaxSource) {
        $(target).dataTable({
            "iDisplayLength": 50,
            "oLanguage": {
                "sProcessing": "Подождите..."
            },
            "bDestroy": true,
            //"bStateSave": true,
            "sPaginationType": "bootstrap",
            "bProcessing": true,
            "sAjaxSource": sAjaxSource,
            "aaSorting": [
                [ 0, "asc" ]
            ],
            "aoColumns": [
                { "sType": "formatted-num" },
                { "sType": "formatted-num", "sClass": "sim_id" },
                { "sType": "formatted-num", "sClass": "sim_number" },
                { "sType": "formatted-num" },
                { "bSortable": false, "sClass": "sim_toolbar", "sType": "html"}
            ]
        });

    }
</script>
<script type="text/javascript">
    $(document).ready(function () {
        loadDataSim('#sim_list_table', 'ajax/loadListSim.php');
    });
</script>
<!-- jQuery form -->
<script type="text/javascript">
    //Upload
    $("#buttonUpload").click(function () {
        ajaxFileUpload();
    });
    function parseCsv(csv) {
        alert(csv);
    }


    function ajaxFileUpload() {
        $("#loading")
            .ajaxStart(function () {
                $(this).show();
            })
            .ajaxComplete(function () {
                $(this).hide();
            });

        $.ajaxFileUpload
        (
            {
                url: 'ajax/doajaxfileupload.php',
                secureuri: false,
                fileElementId: 'fileToUpload',
                dataType: 'json',
                data: {name: 'logan', id: 'id'},
                success: function (data, status) {
                    if (typeof(data.error) != 'undefined') {
                        if (data.error != '') {
                            //alert(data.error);
                            $.sticky(data.error, {autoclose: 3000, position: "top-center", type: "st-error"});
                        } else {
                            //alert(data.msg);
                            //data = eval("(" + data + ")");
                            //console.log(data);
                            $("#buttonUpload").hide();
                            $(".uneditable-input .fileupload-preview").text('');
                            $.sticky(data.msg, {autoclose: 6000, position: "top-center", type: "st-success"});
                            var csv = data.csv
                            parseCsv(csv);
                        }
                    }
                },
                error: function (data, status, e) {
                    alert(e);
                }
            }
        )

        return false;

    }


    $(document).ready(function () {
        $(':file').change(function () {
            var file = this.files[0];
            name = file.name;
            size = file.size;
            type = file.type;
            //your validation
            if (type != 'application/vnd.ms-excel') {
                $(".uneditable-input .fileupload-preview").text('');
                $("#buttonUpload").hide();
                $.sticky('Только CSV файлы!', {autoclose: 3000, position: "top-center", type: "st-error"});
                return false;
            } else {
                $("#buttonUpload").show();
            }
        });

        // bind form using ajaxForm
        $('#create_sim').ajaxForm({
            beforeSubmit: validate,
            // dataType identifies the expected content type of the server response
            dataType: 'json',
            // success identifies the function to invoke when the server response
            // has been received
            success: processJson
        });
    });
    function processJson(data) {
        // 'data' is the json object returned from the server
        loadDataSim('#sim_list_table', 'ajax/loadListSim.php');
        $.sticky(data.message, {autoclose: 6000, position: "top-center", type: data.type});
        $('#create_sim').trigger('reset');
    }
    function validate(formData, jqForm, options) {
        // formData is an array of objects representing the name and value of each field
        // that will be sent to the server;  it takes the following form:
        //
        // [
        //     { name:  username, value: valueOfUsernameInput },
        //     { name:  password, value: valueOfPasswordInput }
        // ]
        //
        // To validate, we can examine the contents of this array to see if the
        // username and password fields have values.  If either value evaluates
        // to false then we return false from this method.


        if ($("#create_sim_number").val() == '') {
            bootbox.alert("Укажите правильный номер", function () {
            });
            return false;
        }
    }
</script>